package com.dongdong.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbSeller;
import com.dongdong.pojo.User;
import com.dongdong.service.SellerService;
import com.dongdong.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/7 11:22
 * @Version 1.0
 **/
public class LoginUserRealm extends AuthorizingRealm {

    @Reference
    private SellerService sellerService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权逻辑");
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        TbSeller seller = (TbSeller) subject.getPrincipal();
        System.out.println("当前登录用户是 :" + seller.getName());
        String perms = "myadd";
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        List<String> permsList = new ArrayList<>();
        permsList.add(perms);
        auth.addStringPermissions(permsList);
        return auth;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证逻辑");
        //账号是否存在
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //通过账号查询
        String name = token.getUsername();
        TbSeller seller = sellerService.findUserByUserName(name);
        return seller == null ? null : new SimpleAuthenticationInfo(seller,seller.getPassword(), ByteSource.Util.bytes(seller.getTelephone()),seller.getName());
    }
}

